<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-deptName>
                <el-input
                  v-if="isSpecialEdit === 1"
                  v-model="formInfo.data.deptName"
                  disabled
                ></el-input>
                <el-input
                  v-else
                  v-model="formInfo.data.deptName"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择部门"
                >
                  <template #append>
                    <el-icon @click="openDeptWindow"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
            <!-- <div class="model-tips">
              (证照：<span>近效期</span>
              <span class="model-tips-nearly"></span>
            </div>
            <div class="model-tips">
              <span>过期</span>
              <span class="model-tips-expire"></span>)
            </div> -->
          </div>
          <div class="model-panel-body">
            <div class="filter-wrapper">
              <!-- 条件栏 -->
              <page-filter
                v-model:query="filterInfo.query"
                :filter-list="filterInfo.list"
              >
                <template v-slot:filter-addProduct>
                  <el-button :disabled="!canAddProduct" @click="addProduct"
                    >添加资产</el-button
                  >
                </template>
                <template v-slot:filter-removeProduct>
                  <el-button
                    :disabled="!canRemoveProduct"
                    @click="removeProduct()"
                    >删除资产</el-button
                  >
                </template>
              </page-filter>
              <div class="display-flex">
                <el-button @click="preferenceInfo.visible = true"
                  >偏好设置</el-button
                >
              </div>
            </div>

            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  ref="table"
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :tab-index="true"
                  :query="filterInfo.query"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :cell-class-name="tableCellClassName"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-qty="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.qty`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                validator: $validate.positive,
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.qty"
                        clearable
                        controls-position="right"
                        :precision="0"
                        :min="0"
                        :max="99999999"
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-price="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.price`"
                      :rules="
                        scope.$index >= 0
                          ? [
                              {
                                validator: $validate.positive,
                                trigger: 'blur',
                              },
                            ]
                          : []
                      "
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.price"
                        clearable
                        :disabled="
                          !!(
                            formInfo.data.contractId &&
                            formInfo.data.contractId != -2
                          )
                        "
                        controls-position="right"
                        :precision="systemConfig.qty_show_precision"
                        :min="0"
                        :max="99999999"
                      />
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!--资产选择-->
    <select-equipment-archives
      v-if="selectEquipmentInfo.visible"
      v-model:show-dialog="selectEquipmentInfo.visible"
      :query="selectEquipmentInfo.query.queryMap"
      :query-params="selectEquipmentInfo.query.queryParams"
      :check-box="true"
      @callback="callBackEquipment"
    />
    <selectDept
      v-if="deptInfo.visible"
      v-model:show-dialog="deptInfo.visible"
      :check-box="deptInfo.checkBox"
      :highlight-row="true"
      :query="deptInfo.query"
      :saveEmpty="true"
      @callback="_selectDept"
    />
    <SetPreferenceNoQuery
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
  </div>
</template>

<script setup name="purchApplicationModify">
import PageForm from '@/components/PageForm/index'
import PageTable from '@/components/PageTable/index.vue'
import {
  getAssetPurchApplicationCustomizeListAll,
  createAssetPurchApplication,
  createAssetPurchApplicationAndSave,
  updateAssetPurchApplication,
  submitAssetPurchApplication,
  getAssetPurchApplicationById,
} from '@/api/asset'
import PageFilter from '@/components/PageFilter/index'
import selectDept from '@/components/SelectDept/index'
import { getCoreSystemConfigGetConfigValue } from '@/api/core.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'

const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const SetPreferenceNoQuery = defineAsyncComponent(() =>
  import('@/components/SetPreference/setPreferenceNoQuery')
)

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '',
  },
  orderId: {
    type: [Number, String],
    default: '',
  },
  isSpecialEdit: {
    type: [Number, String],
    default: '',
  },
  isCopy: {
    type: Boolean,
    default: false,
  },
})

const formInfo = reactive({
  ref: null,
  data: {
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    createUserName: proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.name
      : '',
    purchProductType: 2,
  },
  fieldList: [
    {
      label: '创建人',
      value: 'createUserName',
      type: 'input',
      disabled: true,
    },
    { label: '部门', value: 'deptName', type: 'slot' },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    deptName: [{ required: true, message: '请选择部门', trigger: 'change' }],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      deptId: null,
    },
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  selectionsCopy: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
})
const fullInfo = reactive({
  btnList: [
    {
      label: '保存并提交',
      event: saveAndSubmit,
      show:
        (!props.orderId || props.isCopy) &&
        proxy.$permission('assetPurchApplication:saveAndSubmit'),
    },
    { label: '保存', event: save, show: true },
  ],
})
//选择资产相关
let selectEquipmentInfo = reactive({
  visible: false,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  searchList: [],
})
const deptInfo = reactive({
  visible: false,
  checkBox: false,
  query: {
    deptAuth: 'id',
  },
})
const preferenceInfo = reactive({
  visible: false,
})
const formRefs = ref([])
const licencesSystemConfig = ref({})
const tableKey = ref(
  'assetPurchApplicationOrderModify-com.slip.spd.entity.vo.asset.AssetPurchApplicationDetailVO'
)
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canAddProduct = computed(() => {
  return props.isSpecialEdit !== 1
})
const canRemoveProduct = computed(() => {
  return tableInfo.selections.length && props.isSpecialEdit !== 1
})

watch(
  () => tableInfo.data,
  () => {
    tableInfo.data.forEach((row) => {
      row.calcQty = row.qty
      row.sumAmount = proxy.$fn.accMul(
        row.qty,
        parseFloat(row.price == null ? 0 : row.price)
      )
    })
  },
  {
    deep: true,
  }
)

let obj = {
  qty: {
    label: '申购数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    type: 'slot',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('assetPurchApplication:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('assetPurchApplication:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('assetPurchApplication:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()

onMounted(() => {
  getValueList()
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  })
})

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(true)
    }
  })
}
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function addProduct() {
  const idNotIn = tableInfo.data.map(function (item) {
    return item.productId
  })
  selectEquipmentInfo.query.queryMap.id.value = idNotIn.toString()
  selectEquipmentInfo.visible = true
}
//删除资产
function removeProduct() {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      tableInfo.selectionsCopy = proxy.$fn.deepClone(tableInfo.selections)
      tableInfo.data = tableInfo.data.filter(
        (row) => !tableInfo.selections.includes(row)
      )
    })
}

//选择资产
function callBackEquipment(rows) {
  if (rows) {
    const data = rows.map(function (item) {
      return {
        ...item,
        qty: 0,
        price: item.price || 0,
        productId: item.id,
        productCode: item.code,
      }
    })
    tableInfo.data = data.concat(tableInfo.data)
  }
}
function _selectDept(row) {
  if (row) {
    if (row.id !== formInfo.data.deptId) {
      formInfo.data['deptName'] = row.name
      formInfo.data['deptId'] = row.id
    }
  } else {
    formInfo.data['deptName'] = ''
    formInfo.data['deptId'] = ''
  }
}
function openDeptWindow() {
  deptInfo.visible = true
}
function saveAndSubmit() {
  save('', '', '', true)
}
function save(eventObj, isSubmit, ids = undefined, isSaveAndSubmit) {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const details = tableInfo.data.filter((item) => item.calcQty > 0)
    if (details.length === 0) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的资产',
      })
      return
    }
    if (details.length < tableInfo.data.length) {
      proxy
        .$confirm(`存在数量为0的资产，是否继续保存`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(() => {
          checkSave(details, isSubmit, ids, isSaveAndSubmit)
        })
        .catch()
    } else {
      checkSave(details, isSubmit, ids, isSaveAndSubmit)
    }
  })
}
function checkSave(details, isSubmit, ids, isSaveAndSubmit) {
  const data = formInfo.data
  data.isSpecialEdit = props.isSpecialEdit
  data.mergeDetails = proxy.$fn.filterBlacklist(details)
  const api = data.id
    ? updateAssetPurchApplication
    : isSaveAndSubmit === true
    ? createAssetPurchApplicationAndSave
    : createAssetPurchApplication
  api(data).then((resp) => {
    if (resp && resp.success) {
      if (isSubmit) {
        submitAssetPurchApplication(ids).then((resp) => {
          if (resp.success) {
            tableInfo.refresh = Math.random()
            showDialog.value = false
            emit('returnModify', false)
          }
        })
      } else {
        showDialog.value = false
        emit('returnModify', false)
      }
    }
  })
}
//获取申购单明细
function getList() {
  getAssetPurchApplicationCustomizeListAll(filterInfo.query).then((resp) => {
    if (resp && resp.success) {
      if (props.isCopy) {
        resp.data.forEach((val) => {
          val.id = null
          val.orderId = null
          val.prePurchQty = null
          val.prePurchCalcQty = null
          val.actualPurchQty = null
          val.actualPurchCalcQty = null
        })
        tableInfo.data = resp.data
        formInfo.data.id = null
      } else {
        tableInfo.data = resp.data
      }
    }
  })
}
//获取申购单主表
function getMain(orderId) {
  getAssetPurchApplicationById(orderId).then((resp) => {
    if (resp && resp.success) {
      if (props.isCopy) {
        formInfo.data.deptName = resp.data.deptName
        formInfo.data.deptId = resp.data.deptId
      } else {
        formInfo.data = resp.data
      }
      filterInfo.query.queryParams.deptId = formInfo.data.deptId
      getList()
    }
  })
}
function getValueList() {
  getCoreSystemConfigGetConfigValue({
    systemConfigCode: 'license_nearly_effective',
  }).then((resp) => {
    if (resp && resp.success) {
      licencesSystemConfig.value = resp.data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.licenseEndDate) {
    let dataDiff = proxy.$fn.dateDiffLicen(row.licenseEndDate)
    if (dataDiff <= 0) {
      return 'expire-row'
    } else if (Number(licencesSystemConfig.value) >= dataDiff) {
      return 'nearly-row'
    }
  }
  return ''
}
function tableCellClassName({ column, row }) {
  if (row.calcQty === 0 && column.property === 'qty') {
    return 'cell-color'
  }
  return ''
}
function getCustomize(update = undefined) {
  let param = {
    tableKey: tableKey.value,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      filterInfo.query.customizeUserVO = data
      filterInfo.query.queryMap.orderId.value = props.orderId
      if (update) {
        let arr = []
        for (let key in data.detail) {
          arr.push(data.detail[key])
        }
        let sortArr = []
        arr.forEach((item) => {
          if (item.sortControllerType === 1) {
            sortArr.push({
              prop: item.fieldName,
              order: 'ascending',
            })
          } else if (item.sortControllerType === 2) {
            sortArr.push({
              prop: item.fieldName,
              order: 'descending',
            })
          }
        })
        if (sortArr.length) {
          proxy.$refs.table.$refs.table.sort(sortArr[0].prop, sortArr[0].order)
        }
        return
      }
      if (props.orderId) {
        getMain(props.orderId)
      }
    }
  })
}
</script>

<style scoped lang="scss">
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table .nearly-row) {
  background: #fceacb;
}
:deep(.el-table .expire-row) {
  background: #f5e4e4;
}
:deep(.el-table .cell-color) {
  background: #f4aed9bd;
}
</style>
